package com.ruoyi.purchaseReturn.controller;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyInvoice;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.mapper.CompanyMapper;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.procurement.domain.ProcurementModel;
import com.ruoyi.procurement.domain.ProcurementOrder;
import com.ruoyi.procurement.service.ProcurementServer;
import com.ruoyi.product.domain.Product;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnModel;
import com.ruoyi.purchaseReturn.domain.PurchaseReturnOrder;
import com.ruoyi.purchaseReturn.service.IPurchaseReturnService;
import com.ruoyi.sale.domain.SaleorderModel;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.warehousing.domain.Warehousing;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author WangChangShuo
 * @date 2022年06月15日 11:22
 */
@RestController
@RequestMapping("/business/purchaseReturn")
public class PurchaseReturnContrller extends BaseController {

    private String prefix = "purchaseReturn";
    @Autowired
    IPurchaseReturnService iPurchaseReturnService;

    @Autowired
    ISaleorderService iSaleorderService;

    @Autowired
    ProcurementServer procurementServer;

    @Autowired
    AuditService auditService;

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    ICompanyInvoiceService iCompanyInvoiceService;

    @Autowired
    PurchaseOrderService purchaseOrderService;

    @Autowired
    ISysDeptService iSysDeptService;

    @Autowired
    ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    CompanyMapper companyMapper;

    @RequiresPermissions("business:purchaseReturn:view")
    @GetMapping()
    public String order(Model model) {
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
        purchaseReturnOrder.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<PurchaseReturnOrder> list = iPurchaseReturnService.selectPurchaseReturnOrder(purchaseReturnOrder);
        Set<String> set = new HashSet<String>();
        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i).getDeptName());
        }
        set.removeIf(Objects::isNull);
        model.addAttribute("custObj", set);
        return prefix + "/list";
    }

    /**
     * 查询采购退货列表
     */
    @RequiresPermissions("business:purchaseReturn:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "deptName", required = false) String deptName,
                              @RequestParam(value = "purchaseReturnStatus", required = false) String purchaseReturnStatus,
                              @RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime) {
        PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
        purchaseReturnOrder.setDeptName(deptName);
        purchaseReturnOrder.setPurchaseReturnStatus(purchaseReturnStatus);
        purchaseReturnOrder.setBeginTime(beginTime);
        purchaseReturnOrder.setEndTime(endTime);
        startPage();
        purchaseReturnOrder.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<PurchaseReturnOrder> list = iPurchaseReturnService.selectPurchaseReturnOrder(purchaseReturnOrder);
        return getDataTable(list);
    }

    /**
     * 新增采购退货单
     */
    @GetMapping("/selectInformation")
    public Map<String, Object> add() {
        Map<String, Object> resMap = new HashMap<>();
        Long companyId = SecurityUtils.getLoginUser().getUser().getCompanyId();
        List<SysUser> user = iSysUserService.selectSalesmanList(companyId);
        if (user != null) {
            resMap.put("user", user);
        }
        return resMap;
    }

    /**
     * 选择入库单界面
     */
    @GetMapping("/selectProcurement")
    public Map<String, Object> selectProcurement() {
        Map<String, Object> resMap = new HashMap<>();
        List<PurchaseReturnOrder> list = iPurchaseReturnService.selectProcurementSupplierObj(SecurityUtils.getLoginUser().getUser().getCompanyId());
        resMap.put("SupplierObj", list);
        return resMap;
    }

    @GetMapping("/auditSale")
    @ResponseBody
    public AjaxResult auditSale(@RequestParam(value = "purchaseReturnId", required = false) Long purchaseReturnId,
                                @RequestParam(value = "purchaseReturnStatus", required = false) String purchaseReturnStatus) {
        PurchaseReturnOrder purchaseReturnOrder = new PurchaseReturnOrder();
        purchaseReturnOrder.setPurchaseReturnId(purchaseReturnId);
        purchaseReturnOrder.setPurchaseReturnStatus(purchaseReturnStatus);
        return toAjax(iPurchaseReturnService.auditSale(purchaseReturnOrder));
    }

    /**
     * 选择采购入库订单列表 post
     */
    @GetMapping("/selectProcurementOrderList")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "supplierId", required = false) Long supplierId,
                              @RequestParam(value = "beginTime", required = false) String beginTime,
                              @RequestParam(value = "endTime", required = false) String endTime) {
        ProcurementOrder procurementOrder = new ProcurementOrder();
        procurementOrder.setSupplierId(supplierId);
        procurementOrder.setBeginTime(beginTime);
        procurementOrder.setEndTime(endTime);
        startPage();
        procurementOrder.setDeptId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<ProcurementOrder> list = iPurchaseReturnService.selectProcurementOrderListByReturn(procurementOrder);
        return getDataTable(list);
    }

    /**
     * 选择采购单 子表的数据
     */
    @GetMapping("/selectProcurementModelList")
    @ResponseBody
    public TableDataInfo selectProcurementModelList(@RequestParam(value = "procurementWarehousingId", required = false) Long procurementWarehousingId) {
        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("procurementWarehousingId", procurementWarehousingId);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<ProcurementModel> purchaseModels = iPurchaseReturnService.selectProcurementModelById(hashMap);
        for (ProcurementModel procurementModel : purchaseModels) {
            if (procurementModel.getUnit().equals("盒") || procurementModel.getUnit() == "盒") {
                procurementModel.setAllNum(procurementModel.getAllNum() / procurementModel.getFactor());
            }
        }
        return getDataTable(purchaseModels);
    }

    /**
     *
     */
    @PostMapping("/selectProcurementById")
    @ResponseBody
    public ProcurementOrder selectProcurementById(Long procurementWarehousingId) {
        HashMap hashMap = new HashMap();
        hashMap.put("procurementWarehousingId", procurementWarehousingId);
        ProcurementOrder procurementOrder = iPurchaseReturnService.selectProcurementOrderById(procurementWarehousingId);
        return procurementOrder;
    }

    /**
     * 选择产品
     */
    @GetMapping("/selectProduct/{procurementWarehousingId}")
    public String selectProductget(@PathVariable("procurementWarehousingId") String procurementWarehousingId, Model model) {
        model.addAttribute("procurementWarehousingId", procurementWarehousingId);
        return prefix + "/selectProduct";
    }

    /**
     * 选择产品 主表的数据
     */
    @GetMapping("/selectProcurementModelLists/{procurementWarehousingId}")
    @ResponseBody
    public TableDataInfo selectSaleModelList(@PathVariable("procurementWarehousingId") Long procurementWarehousingId) {
        startPage();
        HashMap hashMap = new HashMap();
        hashMap.put("procurementWarehousingId", procurementWarehousingId);
        hashMap.put("deptId", SecurityUtils.getLoginUser().getUser().getCompanyId());
        List<ProcurementModel> procurementModels = iPurchaseReturnService.selectProcurementModelById(hashMap);
        if (procurementModels != null) {
            return getDataTable(procurementModels);
        } else {
            List<SaleorderModel> list = new ArrayList();
            return getDataTable(list);
        }
    }

    /*
     * 选择销售订单 子表的数据
     */
    @PostMapping("/selectWarehousing")
    @ResponseBody
    public TableDataInfo selectWarehousing(Long productId, String productType) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
        hashMap.put("productId", productId);
        hashMap.put("productType", productType);
        List<Warehousing> warehousing = iSaleorderService.selectWarehousing(hashMap);
        return getDataTable(warehousing);
    }

    /**
     * 选择产品批次 带出数据
     */
    @PostMapping("/selectSaleorderModel")
    @ResponseBody
    public List<ProcurementModel> selectProcurementModel(String data, Long procurementWarehousingId) {
        JSONArray jsonArray = JSONArray.parseArray(data);
        List<ProcurementModel> saleGoodsModels = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            com.alibaba.fastjson.JSONObject jsonObject = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
            //唯一码
            Object modelCode = jsonObject.get("modelCode");
            //批次
            Object batch = jsonObject.get("batch");
            //出库数量
            Object num = jsonObject.get("num");
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("modelCode", modelCode);
            hashMap.put("batch", batch);
            hashMap.put("procurementWarehousingId", procurementWarehousingId);
            hashMap.put("deptId", ShiroUtils.getSysUser().getCompanyId());
            //退货数量
            hashMap.put("num", num);
            ProcurementModel procurementModel = iPurchaseReturnService.selectProcurementModels(hashMap);
            saleGoodsModels.add(procurementModel);
        }
        return saleGoodsModels;
    }

    /**
     * 新增保存采购退货订单
     */
    @RequiresPermissions("business:purchaseReturn:add")
    @Transactional
    @Log(title = "新增保存采购退货订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@RequestBody PurchaseReturnOrder purchaseReturnOrder) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (purchaseReturnOrder.getPurchaseReturnModels() == null) {
            return AjaxResult.error("请选择退货的产品");
        }
        //创建采购订单
        purchaseReturnOrder.setPurchaseReturnStatus("0");
        purchaseReturnOrder.setPurchaseReturnDate(DateUtils.getNowDate());
        purchaseReturnOrder.setCreateBy(sysUser.getNickName());
        purchaseReturnOrder.setDeptId(sysUser.getCompanyId());

        ProcurementOrder procurementOrder1 = procurementServer.selectProcurementById(purchaseReturnOrder.getProcurementWarehousingId());
        purchaseReturnOrder.setCompanyId(procurementOrder1.getSupplierId());
        int i = iPurchaseReturnService.insertPurchaseReturnOrder(purchaseReturnOrder);
        if (purchaseReturnOrder.getPurchaseReturnModels() != null) {
            iPurchaseReturnService.insertPurchaseReturnModel(purchaseReturnOrder);
        }
        //添加审核订单
        Audit audit = new Audit();
        //销售订单Id
        audit.setOrderId(purchaseReturnOrder.getPurchaseReturnId());
        //登陆人的companyid
        audit.setCompanyId(sysUser.getCompanyId());
        //主表的含税金额
        audit.setTaxAmount(purchaseReturnOrder.getTaxAmount());
        //业务员id
        audit.setUserId(purchaseReturnOrder.getUserId());
        //根据采购入库表id 查询客户id
        ProcurementOrder procurementOrder = procurementServer.selectProcurementById(purchaseReturnOrder.getProcurementWarehousingId());
        //客户id
        audit.setSupplierId(procurementOrder.getSupplierId());
        //订单编号
        audit.setOrderNum(procurementOrder.getProcurementWarehousingName());
        //5为采购退货
        audit.setOrderType("5");
        //状态0为 未审核
        audit.setAuditStatus("0");
        int insertAudit = auditService.insertAudit(audit);
        //修改该采购入库订单 将是否生成退货 单 改为1
        int isReturn = iPurchaseReturnService.updatePurchaseIsReturn(purchaseReturnOrder.getProcurementWarehousingId());

        if (insertAudit >= 1 && i >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    /**
     * 修改采购退货订单
     */
//    @GetMapping("/edit/{purchaseReturnId}")
//    public String edit(@PathVariable("purchaseReturnId") Long purchaseReturnId, ModelMap mmap) {
//        PurchaseReturnOrder purchaseReturnOrder = iPurchaseReturnService.selectPurchaseReturnById(purchaseReturnId);
//        if (purchaseReturnOrder.getPurchaseReturnModels().get(0).getPurchaseReturnModelId()==null){
//            List<PurchaseReturnModel> list = new ArrayList();
//            purchaseReturnOrder.setPurchaseReturnModels(list);
//            mmap.put("purchaseReturnOrder",purchaseReturnOrder);
//        }else {
//            mmap.put("purchaseReturnOrder",purchaseReturnOrder);
//        }
//        List<SysUser> sysUsers = iSysUserService.selectSupplierById(ShiroUtils.getSysUser().getCompanyId());
//        List<SysUser> user = iSysUserService.selectSalesmanList(ShiroUtils.getSysUser().getCompanyId());
//        Product product = new Product();
//        product.setDeptId(ShiroUtils.getSysUser().getCompanyId());
//        Map<String,Object> map1 = new HashMap<>();
//        map1.put("deptId",ShiroUtils.getSysUser().getCompanyId());
//        List<ProductModel> list = iSaleorderService.selectProductList(map1);
//        CompanyInvoice companyInvoice = iCompanyInvoiceService.selectByCompanyId(ShiroUtils.getSysUser().getCompanyId());
//        if (sysUsers!=null){
//            mmap.addAttribute("sysUsers",sysUsers);
//        }
//        if (user!=null){
//            mmap.addAttribute("user",user);
//        }
//        if (list!=null){
//            mmap.addAttribute("products",list);
//        }
//        if (companyInvoice!=null){
//            mmap.addAttribute("taxRate",companyInvoice.getTaxRate());
//        }
////        int taxRate = saleorderOrder.getTaxRate();
////        mmap.addAttribute("taxRate",taxRate);
//        return prefix + "/edit";
//    }

    /**
     * 删除采购退货订单
     */
    @RequiresPermissions("business:purchaseReturn:remove")
    @Log(title = "删除采购退货订单", businessType = BusinessType.DELETE)
    @GetMapping("/remove/{purchaseReturnId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("purchaseReturnId") Long purchaseReturnId) {
        return toAjax(iPurchaseReturnService.deletePurchaseReturnById(purchaseReturnId));
    }

    /**
     * 查看采购退货订单
     */
    @GetMapping("/findPurchaseReturn/{purchaseReturnId}")
    public Map<String, Object> findPurchaseReturn(@PathVariable("purchaseReturnId") Long purchaseReturnId) {
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        PurchaseReturnOrder purchaseReturnOrder = iPurchaseReturnService.selectPurchaseReturnById(purchaseReturnId);
        List<ProcurementModel> procurementModelList = new ArrayList<>();
        if (purchaseReturnOrder.getPurchaseReturnModels().get(0).getPurchaseReturnModelId() == null) {
            List<PurchaseReturnModel> list = new ArrayList();
            purchaseReturnOrder.setPurchaseReturnModels(list);
            resMap.put("purchaseReturnOrder", purchaseReturnOrder);
        } else {
            //查询 采购入库单的信息 set进model 中
            List<PurchaseReturnModel> purchaseReturnModels = purchaseReturnOrder.getPurchaseReturnModels();
            for (int i = 0; i < purchaseReturnModels.size(); i++) {
                Long procurementWarehousingNo = purchaseReturnModels.get(i).getProcurementWarehousingNo();
                ProcurementModel procurementModel = iPurchaseReturnService.selectProcurementModelByNo(procurementWarehousingNo);

                if (procurementModel.getUnit().equals("盒") || procurementModel.getUnit() == "盒") {
                    procurementModel.setAllNum(procurementModel.getAllNum() / procurementModel.getFactor());
                }
                purchaseReturnModels.get(i).setProcurementModel(procurementModel);
                procurementModel.setReturnNum(purchaseReturnModels.get(i).getReturnNum());
                procurementModelList.add(procurementModel);
            }
            resMap.put("purchaseReturnOrder", purchaseReturnOrder);
            resMap.put("procurementModel", procurementModelList);
        }
        Product product = new Product();
        product.setDeptId(sysUser.getCompanyId());
        Map<String, Object> map1 = new HashMap<>();
        map1.put("deptId", sysUser.getCompanyId());
        List<ProductModel> list = iSaleorderService.selectProductList(map1);
        Company companyInvoice = companyMapper.selectByCompanyId(sysUser.getCompanyId());
        if (list != null) {
            resMap.put("products", list);
        }
        if (companyInvoice != null) {
            resMap.put("taxRate", companyInvoice.getTaxRate());
        }
        //供应商
        Long procurementWarehousingId = purchaseReturnOrder.getProcurementWarehousingId();
        ProcurementOrder procurementOrder = procurementServer.selectProcurementById(procurementWarehousingId);
        Long supplierId = procurementOrder.getSupplierId();
        SysDept sysDept = iSysDeptService.selectDeptById(supplierId);
        String supplierName = null;
        if (sysDept != null) {
            supplierName = sysDept.getDeptName();
        }
        resMap.put("supplierName", supplierName);

        // 获取上一条临近的ID
        resMap.put("previousId", iPurchaseReturnService.querypreviousId(purchaseReturnId));
        // 获取下一条临近的ID
        resMap.put("nextId", iPurchaseReturnService.queryNextId(purchaseReturnId));
        return resMap;
    }

    /**
     * 查询供应商的绑定业务员
     */
    @GetMapping("/selectUser/{companyId}")
    @ResponseBody
    public AjaxResult selectUser(@PathVariable("companyId") Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getCompanyId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }
}
